# 用于下载云学堂中课件,生成pdf
from selenium import webdriver
from selenium.webdriver.common.by import By

from lxml import etree
import sys
import getwebhtml
import downloadpicture
import pic2pdf
import urllib.request
import time
from datetime import datetime
import os

ProjectDir = os.path.dirname(os.path.realpath(sys.argv[0])) + '/'

# 读取自动登陆密码
def read_login_info():
    info = []
    try:
        with open(ProjectDir+'login','r',encoding='utf-8') as f:
            for line in f.read().split('\n'):
                if not line.startswith('#') and line:
                    info.append(line)
    except:
        pass
    return info

# 激活判定程序
def activation():
    target_time = '2023-12-31 23:59:59'
    format_pattern = '%Y-%m-%d %H:%M:%S'
    url = 'https://beijing-time.org/'
    response = urllib.request.Request(url=url)
    try:
        request_result = urllib.request.urlopen(response)
        headers = request_result.headers
        net_date = headers.get("date")
        gmt_time = time.strptime(net_date[5:25], "%d %b %Y %H:%M:%S")
        bj_timestamp = int(time.mktime(gmt_time) + 8 * 60 * 60)
        bj_time = datetime.fromtimestamp(bj_timestamp)
        difference = (bj_time - datetime.strptime(target_time, format_pattern))
        if difference.days < 0:
            print('授权检测通过，剩余授权天数: {} 天。授权到期时间： {}'.format(abs(difference.days), target_time))
        else:
            print('软件已过期。请重新获取软件授权。授权到期时间： {}'.format(target_time))
            sys.exit()
    except:
        print('网络异常')
        sys.exit()



# 检查网页是否为登陆登陆页面
def __check_login_by_extree(driver):
    html = etree.HTML(driver.page_source)
    title = html.xpath('//title/text()')[0]
    if title == '登录页面 - 麒麟软件在线学习平台':
        print('这是登陆界面')
        return 1
    print('不是登陆界面')
    return 0

# 检查网页是否有学习资料
def __check_study_by_extree(driver):
    html = etree.HTML(driver.page_source)
    word = html.xpath('//*[@id="docplayercontainer"]')
    if word:
        print('发现课件')
        return 1
    print('不是课件界面')
    return 0

if __name__ == '__main__':
    activation()
    driver = webdriver.Chrome()
    # driver = webdriver.Firefox()
    driver.get('https://kylinos.yunxuetang.cn')
    driver.implicitly_wait(3)
    driver.maximize_window()
    # 自动登陆
    login_info = read_login_info()
    if len(login_info)==2:
        driver.find_element(By.CLASS_NAME,'txtloginname').send_keys(login_info[0])
        driver.find_element(By.CLASS_NAME,'txtloginpwd').send_keys(login_info[1])
        driver.find_element(By.ID, 'chkloginpass').click()
        driver.find_element(By.ID, 'btnLogin2').click()
    # 登陆后
    over_handles_list = []
    while 1:
        info = input('请输入操作: ')
        if info == 'd':
            # 切换到浏览器正在显示的标签页
            for handle in driver.window_handles:
                if not handle in over_handles_list:
                    over_handles_list.append(handle)
                    driver.switch_to.window(handle)
                    if __check_study_by_extree(driver):
                        title,picturelist = getwebhtml.main(driver)
                        downloadpicture.main(title, picturelist)
                        pic2pdf.main(title)
        elif info == 'q':   # 退出按键
            driver.quit()
            sys.exit(0)
        else:
            print('请重新输入')



